﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace PayloadTracker.OSM
{
    public partial class TilePrecacherDialog : Form
    {
        double Lat;
        double Long;
        int Zoom;
        int Range;

        Tiles.TilePrecacher m_Precacher;
        public void SetCenter(Coordinate c)
        {
            txtLat.Text = c.Lat.ToString();
            txtLong.Text = c.Long.ToString();
        }

        public TilePrecacherDialog()
        {
            InitializeComponent();

            //2 threads maximum as allowed by OSM.
            m_Precacher = new Tiles.TilePrecacher(2);
            m_Precacher.Start += new Tiles.TilePreacherEvent(m_Precacher_Start);
            m_Precacher.Update += new Tiles.TilePreacherEvent(m_Precacher_Update);
            m_Precacher.Finish += new Tiles.TilePreacherEvent(m_Precacher_Finish);

        }

        void m_Precacher_Finish()
        {
            btnPrecache.BeginInvoke((MethodInvoker)delegate()
            {
                btnPrecache.Enabled = true;
            });
        }

        void m_Precacher_Update()
        {
            lblStatus.BeginInvoke((MethodInvoker)delegate()
            {
                lblStatus.Text = m_Precacher.Completed + "/"+m_Precacher.Total; 
            });
            progressBar1.BeginInvoke((MethodInvoker)delegate()
            {
                progressBar1.Value = ((int) (100 * m_Precacher.Progress));
            });
        }

        void m_Precacher_Start()
        {
            
        }

        private bool ValidateInput()
        {
            try
            {
                Lat = double.Parse(txtLat.Text);
                Long = double.Parse(txtLong.Text);
                Zoom = ((int)numZoom.Value);
                Range = ((int)numRange.Value);

            }
            catch (System.Exception)
            {
            	return false;
            }
            return true;
        }
        private void btnPrecache_Click(object sender, EventArgs e)
        {
            if(!ValidateInput())
            {
                MessageBox.Show("Invalid input.","Error",MessageBoxButtons.OK,MessageBoxIcon.Error);
                return;
            }

            m_Precacher.Precache(new Coordinate(Lat, Long), Range, 2, Zoom);
            btnPrecache.Enabled = false;
            btnCancel.Enabled = true;
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            btnPrecache.Enabled = true;
            btnCancel.Enabled = false;

            m_Precacher.Cancel();
        }


    }
}
